package other.xsy.paas;

import com.rkhd.platform.sdk.data.model.Booking__c;
import com.rkhd.platform.sdk.data.model.Order;
import com.rkhd.platform.sdk.data.model.OrderProduct;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.xsy.paas.utils.HCXObjectService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述：没有Debooking类型数据时，取消归档删除关联了订单明细的Booking类型数据。有Debooking类型数据，不能取消归档，提示：有debooking数据,无法取消订单归档！
 *
 * @author whz
 * @ClassName: OrderUpdateTrigger
 * @Description:
 * @date 2024年03月30日
 */
public class OrderUpdateTrigger implements Trigger {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static Logger logger = LoggerFactory.getLogger();

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Order> orderList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Order order = (Order) xObject;
            orderList.add(order);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        handler(orderList.get(0), dataResultList.get(0));
        return new TriggerResponse(true, "", dataResultList);
    }

    public void handler(Order order, DataResult dataResult) {
        try {
            logger.info("没有Debooking类型数据时，取消归档删除关联了订单明细的Booking类型数据。有Debooking类型数据，不能取消归档，提示：有debooking数据,无法取消订单归档！");
            logger.info("订单编号：" + order.getPo());
            Integer poStatus = order.getPoStatus();
            Order orderOld = new Order();
            orderOld.setId(order.getId());
            orderOld = hcxObjectService.get(orderOld);
            Integer poStatusOld = orderOld.getPoStatus();
            if (poStatus.equals(poStatusOld)) {
                logger.info("订单状态没有变化");
                return;
            }
            if (poStatus == 1) {
                logger.info("执行失效业务");
                invalid(order.getId(), dataResult);
            }
        } catch (Exception e) {
            logger.error("系统异常：" + e.getMessage());
            dataResult.setSuccess(false);
            dataResult.setMsg("系统异常");
        }
    }

    private void invalid(Long id, DataResult dataResult) throws Exception {
        String sql = "select id,name,bookingType__c,orderDetails__c,order__c from booking__c where order__c = " + id + " and orderDetails__c is not null";
        List<Booking__c> bookingList = (List<Booking__c>) hcxObjectService.queryAll(sql);
        if (bookingList == null || bookingList.size() <= 0) {
            return;
        }
        List<Booking__c> collect = bookingList.stream().filter(data -> data.getBookingType__c() == 2).collect(Collectors.toList());
        if (collect.size() > 0) {
            dataResult.setMsg("有debooking数据,无法取消订单归档！");
            dataResult.setSuccess(false);
            return;
        }
        List<Booking__c> collect2 = bookingList.stream().filter(data -> data.getBookingType__c() == 1).collect(Collectors.toList());
        if (collect2.size() <= 0) {
            return;
        }
        BatchOperateResult batchOperateResult = hcxObjectService.batchDelete2(collect2);
        if (batchOperateResult.getSuccess()) {
            return;
        }
        List<OperateResult> operateResults = batchOperateResult.getOperateResults();
        List<Long> successIdList = operateResults.stream().filter(data -> data.getDataId() != null).map(OperateResult::getDataId).collect(Collectors.toList());
        logger.info("删除成功数量：" + successIdList.size());
        List<OrderProduct> orderProductList = new ArrayList<>();
        for (Booking__c booking : collect2) {
            Long id1 = booking.getId();
            boolean contains = successIdList.contains(id1);
            if (!contains) {
                continue;
            }
            Long orderProductId = booking.getOrderDetails__c();
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setId(orderProductId);
            orderProduct.setYN__c(2); // 是否已经booking
            orderProductList.add(orderProduct);
        }
        if (orderProductList.size() > 0) {
            hcxObjectService.batchUpdate(orderProductList);
        }
        dataResult.setMsg("存在booking数据被debooking、应收明细关联，无法删除");
        dataResult.setSuccess(false);
    }

//    private void takeEffect(Long id, DataResult dataResult) throws ApiEntityServiceException {
//        String sql = "select id,name from booking__c where order__c = " + id + " and bookingType__c = 2";
//        Booking__c booking = hcxObjectService.queryOne(sql);
//        if (booking == null) {
//            return;
//        }
//        dataResult.setSuccess(false);
//        dataResult.setMsg("有debooking数据,无法订单归档！");
//    }
}
